package com.ruoyi.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.PatternMatchUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;

/**
 * 安全服务工具类
 * 
 * @author ruoyi
 */
public class SecurityUtils
{

    /**
     * 用户ID
     **/
    public static Long getUserId()
    {
        try
        {
            System.out.println("[DEBUG] SecurityUtils.getUserId() - 开始获取用户ID");
            LoginUser loginUser = getLoginUser();
            System.out.println("[DEBUG] SecurityUtils.getUserId() - 获取到LoginUser: " + (loginUser != null ? "不为空" : "为空"));
            if (loginUser != null) {
                Long userId = loginUser.getUserId();
                System.out.println("[DEBUG] SecurityUtils.getUserId() - 用户ID: " + userId);
                return userId;
            }
            return null;
        }
        catch (Exception e)
        {
            System.out.println("[DEBUG] SecurityUtils.getUserId() - 异常: " + e.getMessage());
            e.printStackTrace();
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId()
    {
        try
        {
            return getLoginUser().getDeptId();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername()
    {
        try
        {
            return getLoginUser().getUsername();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser()
    {
        try
        {
            System.out.println("[DEBUG] SecurityUtils.getLoginUser() - 开始获取登录用户");
            Authentication authentication = getAuthentication();
            System.out.println("[DEBUG] SecurityUtils.getLoginUser() - 获取到Authentication: " + (authentication != null ? "不为空" : "为空"));
            if (authentication != null) {
                Object principal = authentication.getPrincipal();
                System.out.println("[DEBUG] SecurityUtils.getLoginUser() - Principal类型: " + (principal != null ? principal.getClass().getName() : "null"));
                if (principal instanceof LoginUser) {
                    LoginUser loginUser = (LoginUser) principal;
                    System.out.println("[DEBUG] SecurityUtils.getLoginUser() - LoginUser获取成功");
                    if (loginUser.getUser() != null) {
                        System.out.println("[DEBUG] SecurityUtils.getLoginUser() - SysUser: " + (loginUser.getUser() != null ? "不为空" : "为空"));
                        System.out.println("[DEBUG] SecurityUtils.getLoginUser() - SysUser.getRoles(): " + (loginUser.getUser().getRoles() != null ? "不为空，大小:" + loginUser.getUser().getRoles().size() : "为空"));
                    }
                    return loginUser;
                }
            }
            return null;
        }
        catch (Exception e)
        {
            System.out.println("[DEBUG] SecurityUtils.getLoginUser() - 异常: " + e.getMessage());
            e.printStackTrace();
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId)
    {
        return userId != null && 1L == userId;
    }

    /**
     * 验证用户是否具备某权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(String permission)
    {
        return hasPermi(getLoginUser().getPermissions(), permission);
    }

    /**
     * 判断是否包含权限
     * 
     * @param authorities 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(Collection<String> authorities, String permission)
    {
        return authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> Constants.ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, permission));
    }

    /**
     * 验证用户是否拥有某个角色
     * 
     * @param role 角色标识
     * @return 用户是否具备某角色
     */
    public static boolean hasRole(String role)
    {
        System.out.println("[DEBUG] SecurityUtils.hasRole() - 开始验证角色: " + role);
        try {
            LoginUser loginUser = getLoginUser();
            System.out.println("[DEBUG] SecurityUtils.hasRole() - 获取到LoginUser: " + (loginUser != null ? "不为空" : "为空"));
            if (loginUser != null && loginUser.getUser() != null) {
                System.out.println("[DEBUG] SecurityUtils.hasRole() - SysUser不为空，准备获取角色列表");
                List<SysRole> roleList = loginUser.getUser().getRoles();
                System.out.println("[DEBUG] SecurityUtils.hasRole() - 角色列表: " + (roleList != null ? "不为空，大小:" + roleList.size() : "为空"));
                
                // 如果角色列表为空，创建默认角色
                if (roleList == null || roleList.isEmpty()) {
                    System.out.println("[DEBUG] SecurityUtils.hasRole() - 角色列表为空，设置默认角色2");
                    SysRole defaultRole = new SysRole();
                    defaultRole.setRoleId(2L);
                    defaultRole.setRoleKey("common");
                    defaultRole.setRoleName("普通角色");
                    roleList = new ArrayList<>();
                    roleList.add(defaultRole);
                }
                
                Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
                return hasRole(roles, role);
            }
            return false;
        } catch (Exception e) {
            System.out.println("[DEBUG] SecurityUtils.hasRole() - 异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断是否包含角色
     * 
     * @param roles 角色列表
     * @param role 角色
     * @return 用户是否具备某角色权限
     */
    public static boolean hasRole(Collection<String> roles, String role)
    {
        return roles.stream().filter(StringUtils::hasText)
                .anyMatch(x -> Constants.SUPER_ADMIN.equals(x) || PatternMatchUtils.simpleMatch(x, role));
    }

    /**
     * 获取用户组织ID
     * 
     * @return 组织ID
     */
    public static Long getOrgId()
    {
        try
        {
            LoginUser loginUser = getLoginUser();
            if (loginUser != null && loginUser.getUser() != null) {
                // 根据用户的部门ID映射到对应的组织ID
                Long deptId = loginUser.getDeptId();
                if (deptId != null) {
                    // 部门ID到组织ID的映射逻辑
                    // 115部门对应115组织，103部门对应103组织，其他部门默认103组织
                    if (deptId.equals(115L)) {
                        return 115L;
                    } else if (deptId.equals(103L)) {
                        return 103L;
                    } else {
                        // 其他部门默认映射到103组织
                        return 103L;
                    }
                }
            }
            return null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

}
